#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include "FileNotFoundException"

int createUsers(const char *fileName, std::vector<user_manager*> &users) {
    int userNums;
    int um_id;
    std::string um_name;
    std::string um_password;
    std::string line;

    std::cout << "从文件" << fileName << "中读入数据，生成书本清单" << std::endl;
    std::ifstream fileStream(fileName);

    if (fileStream.rdstate() & std::ios::failbit) {
        std::ostringstream message;
        message << "不能打开文件" << fileName << "，请确认文件路径是否正确" ;
        throw FileNotFoundException(message.str());
    }

    while (getline(fileStream, line)) {
        std::istringstream strStream(line);
        strStream >> um_id;
        strStream >> um_name >> um_password;
        user_manager* ptr = new user_manager(um_id, um_name, um_password);
        users[userNums++] = ptr;
    }
    for (int i = 0; i < userNums; i ++) users[i]->showInfo();
    return userNums;
}

void outputBinaryFiles(std::vector<user_manager*> &users, int userNums) {
    std::cout << "将数组中的内容写入二进制文件" << std::endl;
    std::ofstream userFile("user_managers.dat", std::ios_base::out | std::ios_base::binary);
    for (int i = 0; i < userNums; i ++ ) {
        userFile.write(reinterpret_cast<char*>(users[i]), sizeof(*users[i]));
    }
    userFile.close();
    std::cout << "二进制文件写入完成。" << std::endl;
}

void readBinaryFiles(std::vector<user_manager*> &users, int userNums) {
    std::cout << "从二进制文件中读取数据。" << std::endl;
    std::ifstream userFile("user_managers.dat", std::ios_base::in | std::ios_base::binary);
    int i = 0;
    while (userFile.read(reinterpret_cast<char*>(users[i]), sizeof(*users[i]))) {
        users[i++]->showInfo();
    }

    userFile.close();
    std::cout << "文件读取操作完成。" << std::endl;
}